package com.ys.service.business.impl;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.entity.business.TpBoutiqueDiscount;
import com.ys.mapper.business.BusinessMapper;
import com.ys.mapper.business.TpBoutiqueDiscountMapper;
import com.ys.service.business.TpBoutiqueDiscountService;
import com.ys.vo.R;

@Service("tpBoutiqueDiscountService")
public class TpBoutiqueDiscountServiceImpl implements TpBoutiqueDiscountService {
	@Autowired
	private BusinessMapper businessMapper;

	@Autowired
	private TpBoutiqueDiscountMapper tpBoutiqueDiscountMapper;

	@Override
	public R setting(String priceArr) {
		
		businessMapper.deleteTysProductDiscount();
		
		JSONArray detailJA = JSON.parseArray(priceArr);
		if (detailJA.size() == 0) {
			return R.error("梯度至少配置一项");
		} else if (detailJA.size() > 5) {
			return R.error("梯度最多配置五项");
		}
		
		BigDecimal amountCurrent = BigDecimal.ZERO;
		BigDecimal discountCurrent = BigDecimal.ONE;
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			
			BigDecimal amount = detailJO.getBigDecimal("amount");
			if (amount == null) {
				return R.error("首次调拨数量不能为空");
			}
			if (amount.compareTo(amountCurrent) < 0) {
				return R.error("总价必须从小到大");
			}
			amountCurrent = amount;
			
			BigDecimal discount = detailJO.getBigDecimal("discount");
			if (discount.compareTo(discountCurrent) > 0) {
				return R.error("折扣必须从大到小");
			}
			discountCurrent = discount;
			
			TpBoutiqueDiscount entity = TpBoutiqueDiscount.tpBoutiqueDiscount(amount, discount, 1);
			
			tpBoutiqueDiscountMapper.insert(entity);
		}
		return R.ok("操作成功");
	}
}
